package com.hehe.controller;




import com.hehe.Common.PayTool;
import com.hehe.Common.StringTool;
import com.hehe.POJO.Orders;
import com.hehe.POJO.Photo;
import com.hehe.Repository.OrdersRepository;
import com.hehe.Repository.PhotoRepository;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Map;
import java.util.Optional;

@Slf4j
@Controller
@RequestMapping(value = "")
public class OrdersPayController {

    @Value("${config_file_name}")
    private String config_file_name;

    @Resource
    private PhotoRepository photoRepository;

    @Resource
    private OrdersRepository ordersRepository;

//    @Resource
//    private UserRepository userRepository;

    //    ResponseBody
    @PostMapping(value = "/api/buy")
    @ResponseBody
    public String ResponseBody_test(@RequestBody Map<String, Object> requestData, HttpServletRequest request) {
        long id = Integer.parseInt(requestData.get("id").toString());
        String username = requestData.get("username").toString();

        // int hash = Objects.hash(id, username); // 使用 Objects.hash 生成哈希值, 返回 int

        Optional<Photo> byId = photoRepository.findById(id);
        if (byId.isPresent()) {
            String orderIdStr = StringTool.getRandomString();
            Photo photo = byId.get();
            BigDecimal price = photo.getPrice();
            double priceDouble = price.doubleValue();  // bigDecimal 转 double

            // 5dm5mia===12===0.02
            // plugins:5dm5mia===12===0.02
            String plugins = username + "===" + photo.getId() + "===" + priceDouble;

//            Orders byUsernameAndPhotoId = ordersRepository.findByUsernameAndPhotoId(username, (int) id);
//            if (byUsernameAndPhotoId != null) {
//                // 已经支付过了
//                orderIdStr = byUsernameAndPhotoId.getOrderId();
//            }
            // 如果已经支付 (订单号相同)
            // 虎皮椒支付 接口 响应的结果是：{"errcode":500,"errmsg":"当前订单号已成功支付！","hash":"07b8e364e905595dcf47189042fb7129"}
            // 还没有支付:
            // 虎皮椒支付 接口 响应的结果是：
            // {"openid":20263100604,
            // "url_qrcode":"https://api.xunhupay.com/payments/alipay/qrcode?id=20263100604&nonce_str=4182407043&time=1724440083&appid=201906167140&hash=8a04917d9b6a57c11ca6a483f6b2d256",
            // "url":"https://api.xunhupay.com/payments/alipay/index?id=20263100604&nonce_str=4872410304&time=1724440083&appid=201906167140&hash=0014270f0f69507eebb38253f6e50d55",
            // "errcode":0,"errmsg":"success!","hash":"f4e677995de119d3a12d104137b62aba"}
            String payResult = PayTool.pay(priceDouble, "摄影", orderIdStr, plugins);
            return payResult;
//            if (payResult.contains("errmsg") && payResult.contains("当前订单号已成功支付")){
//                // 订单已经支付, 保存数据库
//                Orders order = new Orders();
//                order.setUsername(username);
//                order.setPhotoId((int) id);
//                order.setOrderId(orderIdStr);
//                order.setOrderPrice(String.valueOf(priceDouble));
//                ordersRepository.save(order);
//                return photo.getNetdiskLink();  // 获取网盘链接
//            }
//            if (payResult.contains("url_qrcode") && payResult.contains("success")){
//                // 订单未支付, 二维码支付
//                return payResult;
//            }
        }
        return "error";



//        完整的 URL，可以使用 request.getRequestURL() 方法
//        StringBuffer requestURL = request.getRequestURL();
//        String successURL = "";
//        if (requestURL.toString().contains("53jiepai.com")){
//            successURL = "https://www.53jiepai.com";
//        } else {
//            successURL = "http://192.168.8.194:8055";
//        }
//        String username = "visitor";
//        successURL = String.format("%s/buy/success/%d/%s/%s", successURL, id, username, orderIdStr);
    }


    @PostMapping("/api/is_buy")
    @ResponseBody
    public String Respont(@RequestBody Map<String, Object> requestData, HttpServletRequest request) {
        log.info("是否购买...");
        long photo_id = Integer.parseInt(requestData.get("id").toString());
        String username = requestData.get("username").toString();
        Orders orders1 = new Orders();
        orders1.setUsername(username);
        orders1.setOrderPrice("0.01");
        orders1.setPhotoId((int) photo_id);
//        ordersRepository.save(orders1);

        Orders orders = ordersRepository.findByUsernameAndPhotoId(username, (int) photo_id);
        if (orders != null) {
            // 已经支付过了
            log.info("已经支付过了");
            Optional<Photo> photo = photoRepository.findById(photo_id);
            return photo.get().getNetdiskLink();
        }
        return "not_paid";
    }













}




